<?php

/**
 * alltosun.com 订单公用函数 order_helper.php
 * ============================================================================
 * 版权所有 (C) 2009-2014 北京互动阳光科技有限公司，并保留所有权利。
 * 网站地址: http://www.alltosun.com
 * ----------------------------------------------------------------------------
 * 许可声明: 这是一个开源程序，未经许可不得将本软件的整体或任何部分用于商业用途及再发布。
 * ============================================================================
 * $Author: 吴松键 (wusj@alltosun.com) $
 * $Date: 2014-8-8 下午6:52:59 $
 * $Id$
 */
class order_helper
{

    /**
     * 增加订单分支信息
     * @param unknown $order_id 订单id
     * @param unknown $cur_user_info 登录人用户信息
     * @param unknown $store_info 如果是合伙人下达则不需传store_info
     */
    public static function create_order_branch($order_id, $cur_user_info, $store_info = array()) {
        $data_order_branch = array(
            'order_id' => $order_id
        );

        $order_info = _uri('order', array('id' => $order_id));
        if (!$order_info) {
            return false;
        }
        // 合伙人是否开启散装进货奖励
        $dealer_info = user_helper::get_user_info($order_info['agency_id']);
        $is_bbcoin_enable = isset($dealer_info['is_bbcoin_enable']) ? $dealer_info['is_bbcoin_enable'] : 0;
        if ($is_bbcoin_enable) {
            $bbcoin = 0;
            $goods_ids = _model('goods')->getFields('id', array('category_id' => 1));
            $order_relation_list = order_helper::get_order_relation_by_order_id($order_id, '', array(
                'goods_id' => $goods_ids
            ));
            if (!empty($order_relation_list)) {
                // 散装商品箱数
                $goods_num = 0;
                foreach ($order_relation_list as $k => $v) {
                    $goods_num += $v['goods_num'];
                }
                $bbcoin = order_config::$reward['bulk_bbcoin'] * $goods_num;
            }
            $data_order_branch['bbcoin'] = $bbcoin;
            $data_order_branch['is_bbcoin_enable'] = $is_bbcoin_enable;
        }
        if ($store_info) {
            $data_order_branch['store_type'] = $store_info['type'];
        }
        return _model('order_branch')->create($data_order_branch);
    }

    /**
     * 保存订单操作
     *
     * @param $order_id
     * @param $order_cur_progress
     * @param $action
     * @param string $extra
     * @return bool
     * @throws AnException
     */
    public static function record_dealer_order_operation($order_id, $order_cur_progress, $action, $extra = '') {
        if (!$order_id) {
            return false;
        }
        $info = array(
            'order_id' => $order_id,
            'admin_id' => user_helper::get_user_id(),
            'order_cur_progress' => $order_cur_progress,
            'action' => $action,
            'extra' => $extra,
            'add_time' => datetime(),
        );

        $order = _model('order')->read(array('id' => $order_id), ' ORDER BY `id` DESC');
        if ($order) {
            $info['order_pre_progress'] = $order['progress'];
        }

        _model('order_operation')->create($info);
        return true;
    }

    /**
     * 经销商向总部进货订单列表
     * @param unknown_type $agency_id
     * @return unknown
     */
    public static function get_dealers_order_list($agency_id) {
        // 经销商向总部进货订单列表
        $order_list = array();
        $order_filter['type'] = 1;
        $order_filter['user_id'] = $agency_id;
        $order_filter['status'] = 1;
        $order_filter['is_enable'] = 1;

        $order_list = _model('order')->getList($order_filter);
        return $order_list;
    }


    public static function get_dealer_order_operation($order_id) {
        if (empty($order_id)) {
            return null;
        }
        $ret = _model('order_operation')->getList(array('order_id' => $order_id));

        if (!empty($ret)) {
            $operation_list = array();
            foreach ($ret as $item) {
                $operation_list[] = array(
                    order_config::$dealer_order_action[$item['action']],
                    user_helper::get_realname_by_id($item['admin_id']),
                    $item['add_time']
                );
            }

            return $operation_list;
        }

        return null;
    }

    /**
     * 获取当前经销商下门店的所有订单
     *
     * @param $agency_id
     * @return array
     * @throws AnException
     */
    public static function get_dealers_store_order_list($agency_id) {

        $order_filter['type'] = 5;
        $order_filter['agency_id'] = $agency_id;
        $order_filter['status'] = 1;
        $order_filter['is_enable'] = 1;

        $order_list = _model('order')->getList($order_filter);
        return $order_list;
    }


    /**
     * 判断当前订单是否有足够的库存
     * 判断条件：
     *     当前所有已经指派人员后的订单库存 + 当前订单的库存是否 < 当前的库存
     *     只要包含任何一种商品库存不够，就不能提示
     * @param unknown_type $order
     * @return array
     */
    public static function is_order_enough_stock($order_id) {
        $result = array('info' => true);

        $order_info = self::get_order_detail($order_id);
        if (!$order_info) {
            return false;
        }

        // 当前订单商品的数量
        $goods_sku_list = self::get_order_goods_stock($order_id);
        //write_log($goods_sku_list);

        // 已经指派的订单商品数量
        $other_order_sku_list = self::get_order_assigned_stock($order_info['agency_id']);
        $other_order_sku_list[] = $goods_sku_list;

        // 所有订单和当前订单的预计使用的库存
        $order_goods_stock_list = self::sum_order_goods_stock($other_order_sku_list);

        // 总店信息
        $user_store_info = store_helper::get_user_store($order_info['agency_id']);
        if (!$user_store_info) {
            return false;
        }

        // 当前账号的库存列表
        $agency_store_stock_list = store_helper::get_agency_store_stock_list($user_store_info['id']);

        if ($agency_store_stock_list) {
            foreach ($order_goods_stock_list as $k => $v) {
                if ($agency_store_stock_list[$k] < $v) {
                    $result['info'] = false;
                    $result['goods_id'] = $k;
                    $goods_info = goods_helper::get_goods_info($k);
                    $result['message'] = '[' .
                                         $goods_info['title'] .
                                         ']' .
                                         ' 库存不足，需要' .
                                         $v .
                                         $goods_info['unit'] .
                                         '，库中还有' .
                                         $agency_store_stock_list[$k] .
                                         $goods_info['unit'] .
                                         '请先盘点库存';
                    break;
                }
            }
        }

        //write_log($result);
        return $result;
    }

    /**
     * 计算当前经销商已分派的订单商品数量
     */
    private static function sum_order_goods_stock($order_list) {

        if (empty($order_list)) {
            return false;
        }

        $goods = array();

        foreach ($order_list as $order_goods) {
            foreach ($order_goods as $v) {

                $key = $v['goods_id'];
                if (array_key_exists($key, $goods)) {
                    $goods[$key] = $v['goods_num'] + $goods[$key];
                } else {
                    $goods[$key] = $v['goods_num'];
                }
            }
        }

        return $goods;
    }

    /**
     * 获取经销商下所有分配订单的商品库存
     * @param unknown_type $user_id
     */
    private static function get_order_assigned_stock($user_id) {
        $data = array();
        $filter['agency_id'] = $user_id;
        $filter['is_assigned'] = 1;
        $filter['progress <'] = 10;
        $filter['status'] = 1;

        $order_list = _model('order')->getList($filter);
        if ($order_list) {
            foreach ($order_list as $k => $v) {
                $data[] = self::get_order_goods_stock($v['id']);
            }
        }

        return $data;
    }

    /**
     * 获取当前订单的商品数量列表
     * @param unknown_type $order_id
     */
    private static function get_order_goods_stock($order_id) {
        $order_relation_list = self::get_order_relation_by_order_id($order_id);
        if ($order_relation_list) {
            foreach ($order_relation_list as $v) {
                $info['sku_id'] = $v['sku_id'];
                $info['goods_id'] = $v['goods_id'];
                $info['goods_num'] = $v['goods_num'];

                $goods_sku_list[] = $info;
            }
        }

        return $goods_sku_list;
    }

    /**
     * 格式化对外的订单的基本信息
     * @param unknown_type $order_id
     * @return multitype:unknown Ambigous <>
     */
    public static function format_store_sub_info($order_id) {
        $data = array();
        $order_info = self::get_order_info($order_id);
        if ($order_info) {
            $data['add_time'] = $order_info['add_time'];
            $data['agency_id'] = $order_info['agency_id'];
            $data['assigned_id'] = $order_info['assigned_id'];
            $data['deliver_time'] = $order_info['deliver_time'];
            $data['deliver_type'] = $order_info['deliver_type'];
            $data['goods_num'] = $order_info['goods_num'];
            $data['is_assigned'] = $order_info['is_assigned'];
            $data['mobile'] = $order_info['mobile'];
            $data['note'] = $order_info['note'];
            $data['order_no'] = $order_info['order_no'];
            $data['other_assigned_mobile'] = $order_info['other_assigned_mobile'];
            $data['other_assigned_name'] = $order_info['other_assigned_name'];
            $data['price'] = $order_info['price'];
            $data['progress'] = $order_info['progress'];
            $data['store_id'] = $order_info['store_id'];
            $data['type'] = $order_info['type'];
            $data['user_id'] = $order_info['user_id'];
            $data['pay_type'] = $order_info['pay_type'];
            $data['receiver_time'] = $order_info['receiver_time'];
            $data['cancel_order_type'] = $order_info['cancel_order_type'];
            $data['cancel_order_time'] = $order_info['cancel_order_time'];
            $data['cancel_order_user_id'] = $order_info['cancel_order_user_id'];
        }

        return $data;
    }

    /**
     * 获取市场人员的未处理的订单
     */
    public static function get_market_unprocess_order_num($user_id) {
        $filter['assigned_id'] = $user_id;
        $filter['progress'] = 1;
        $filter['status'] = 1;

        return _model('order')->getTotal($filter);
    }

    /**
     * 保存订单操作流水
     * @param unknown_type $order_id
     * @param unknown_type $res_name
     * @param unknown_type $desc
     */
    public static function save_order_status_log($order_id, $res_name, $desc) {
        $data['user_id'] = user_helper::get_user_id();
        $data['order_id'] = $order_id;
        $data['res_name'] = $res_name;
        $data['desc'] = json_encode($desc);
        $data['add_time'] = date('Y-m-d H:i:s');
        return _model('order_status')->create($data);
    }

    /**
     * 调用接口，停止掉支付宝端的订单支付
     * @return $err_msg or boolean true
     */
    public static function alipay_close_trade($order_id_or_info) {
        if (is_numeric($order_id_or_info)) {
            $order_id_or_info = (int)$order_id_or_info;
            if (!$order_id_or_info) {
                return "订单ID不存在";
            }
            $order_info = _model('order')->read($order_id_or_info);
        } else {
            $order_info = $order_id_or_info;
        }
        if (!$order_info) {
            return "订单不存在";
        }
        if ($order_info['pay_type'] != 1) {
            return "此订单不是支付宝交易订单";
        }

        $order_id = $order_info['id'];

        // 判断订单状态是否处于已取消状态
        if (!in_array($order_info['progress'], array('0', '1'))) {
            return "订单没有处于取消（或未支付）状态，不能关闭交易";
        }

        require_once MODULE_PATH . '/openapi/config/alipay_config.php';
        require_once MODULE_PATH . '/openapi/helper/alipay/alipay_submit.class.php';

        $alipay_config = array(
            // @fixed by liw 此三个参数由订单获取
            //'partner'            => Config::get('partner'),
            //'key'                => Config::get('alipay_key'),
            //'seller_email'       => Config::get('seller_email'),
            'input_charset' => Config::get('input_charset'),
            'transport' => Config::get('transport'),
            'sign_type' => Config::get('sign_type'),
            'cacert' => Config::get('cacert'),
            'alipay_gateway_new' => Config::get('alipay_gateway_new'),
        );
        $alipay_config = array_merge($alipay_config, openapi_helper::get_order_pay_account($order_id));

        //构造要请求的参数数组，无需改动
        $parameter = array(
            "service" => "close_trade",
            "partner" => $alipay_config['partner'],
            "trade_no" => $order_info['transaction_id'],
            "out_order_no" => self::order_id_encode($order_id),
            "_input_charset" => trim(strtolower($alipay_config['input_charset']))
        );
        //建立请求
        $alipaySubmit = new AlipaySubmit($alipay_config);
        $html_text = $alipaySubmit->buildRequestHttp($parameter);
        //解析XML
        //注意：该功能PHP5环境及以上支持，需开通curl、SSL等PHP配置环境。建议本地调试时使用PHP开发软件
        $doc = new DOMDocument();
        $doc->loadXML($html_text);

        // 记录log
        _model('close_trade_log')->create(array(
            'order_id' => $order_id,
            'transaction_id' => $order_info['transaction_id'],
            'ret_msg' => $html_text
        ));

        //解析XML
        if (!empty($doc->getElementsByTagName("alipay")->item(0)->nodeValue)) {
            $is_success = $doc->getElementsByTagName("alipay")->item(0)->childNodes->item(0)->nodeValue;
            if ($is_success == 'T') {
                return true;
            } else {
                return "关闭交易错误：" . $doc->getElementsByTagName("alipay")->item(0)->childNodes->item(1)->nodeValue;
            }
        } elseif ($html_text) {
            return $html_text;
        } else {
            return "接口请求失败";
        }
    }

    public static function get_goods_num_by_id($order_id) {
        $order_relation_list = _model('order_relation')->getList(array('order_id' => $order_id, 'status' => 1));
        $goods_num = 0;
        foreach ($order_relation_list as $key => $value) {
            $goods_num += $value['goods_num'];
        }
        return $goods_num;
    }

    public static function get_order_detail($order_id) {
        if (!$order_id) {
            return array();
        }
        $order_info = _uri('order', $order_id);

        if ($order_info) {
            $order_info['order_no'] = order_helper::order_id_encode($order_id);
            return $order_info;
        } else {
            return array();
        }
    }

    //获取订单里面有几款商品
    public static function get_order_goods_total_by_id($order_id) {
        $order_goods_total = _model('order_relation')->getTotal(array('order_id' => $order_id, 'status' => 1));
        return $order_goods_total;
    }

    /**
     * 根据订单状态和类型统计订单数量
     * @param number $progress
     * @param number $type
     * @return number
     */
    public static function get_order_num_by_progress($progress = array(), $type = 1, $filter = array()) {
        if (!$progress) {
            return 0;
        }
        $filter['progress'] = $progress;
        $filter['type'] = $type;
        $filter['status'] = 1;
        if (!isset($filter['is_enable'])) {
            $filter['is_enable'] = 1;
        }

        return _model('order')->getTotal(enable_filter($filter));
    }

    /**
     * 根据订单状态和类型统计订单列表
     * @param number $progress
     * @param number $type
     * @return number
     */
    public static function get_order_list_by_progress($progress = array(), $type = 1, $filter = array()) {
        if (!$progress) {
            return 0;
        }
        $filter['progress'] = $progress;
        $filter['type'] = $type;
        $filter['status'] = 1;
        if (!isset($filter['is_enable'])) {
            $filter['is_enable'] = 1;
        }
        $filter['status'] = 1;
        $device_by = ' ORDER BY `agency_id` DESC ';
        return _model('order')->getList($filter, $device_by);
    }

    /**
     * 根据订单状态和类型还有时间统计订单详细
     * @param number $progress
     * @param number $type
     * @return number
     */
    public static function get_order_agency_ids_by_time($progress = array(), $type = 1, $filter = array()) {
        if (!$progress) {
            return 0;
        }
        $filter['progress'] = $progress;
        $filter['type'] = $type;
        $filter['status'] = 1;
        if (!isset($filter['is_enable'])) {
            $filter['is_enable'] = 1;
        }
        $filter['status'] = 1;
        $half_sql = " GROUP BY `agency_id`  ";
        return _model('order')->getFields('agency_id', $filter, $half_sql);
    }

    /**
     * 根据订单状态和类型还有时间统计订单商店ID
     * @param number $progress
     * @param number $type
     * @return number
     */
    public static function get_store_ids_by_update_time($progress = array(), $type = 1, $filter = array()) {
        if (!$progress) {
            return 0;
        }
        $filter['progress'] = $progress;
        $filter['type'] = $type;
        $filter['status'] = 1;
        if (!isset($filter['is_enable'])) {
            $filter['is_enable'] = 1;
        }
        $filter['status'] = 1;
        $half_sql = " GROUP BY `store_id`  ";
        return _model('order')->getFields('store_id', $filter, $half_sql);
    }

    /**
     * 根据订单状态和类型统计订单金额
     */
    public static function get_order_money_by_progress($progress = array(), $type = 1, $filter = array()) {
        if (!$progress) {
            return 0;
        }
        $filter['progress'] = $progress;
        $filter['type'] = $type;
        $filter['status'] = 1;

        $order_list = _model('order')->getList($filter);
        if (!$order_list) {
            return 0;
        }

        $total_money = 0;
        foreach ($order_list as $k => $v) {
            $total_money += $v['price'];
        }
        return $total_money;
    }

    /**
     * 根据订单状态和类型统计订单商品总数量
     */
    public static function get_order_goods_num($progress = array(), $type = 1, $filter = array()) {
        if (!$progress) {
            return 0;
        }
        $filter['progress'] = $progress;
        $filter['type'] = $type;
        $filter['status'] = 1;

        $order_list = _model('order')->getList($filter);
        if (!$order_list) {
            return 0;
        }

        $total_goods_num = 0;
        foreach ($order_list as $k => $v) {
            $total_goods_num += $v['goods_num'];
        }
        return $total_goods_num;
    }

    /**
     *  通过订单id获取订单状态
     */
    public static function get_order_status($order_id = '') {
        if (!$order_id) {
            return false;
        }
        $order_status = _uri('order', $order_id, 'progress');

        if (!$order_status) {
            return false;
        }

        return $order_status;
    }

    /**
     * 获取订单数量
     */
    public static function get_order_total($progress = 1) {
        $user_id = user_helper::get_user_id();
        $filter = array(
            'user_id' => $user_id,
            'progress' => $progress
        );

        return _model('order')->getTotal($filter);
    }

    public static function get_order_info($order_id) {
        if (!$order_id) {
            return array();
        }

        $order_info = _uri('order', $order_id);
        $order_branch_info = _uri('order_branch', array('order_id' => $order_id));
        if ($order_branch_info) {
            $order_info['is_bbcoin_enable'] = $order_branch_info['is_bbcoin_enable'];
            $order_info['bbcoin'] = $order_branch_info['bbcoin'];
            $order_info['store_type'] = $order_branch_info['store_type'];
        } else {
            $order_info['is_bbcoin_enable'] = 0;
            $order_info['bbcoin'] = 0;
            $order_info['store_type'] = 0;
        }

        return $order_info;
    }

    /**
     * 通过订单id获取订单分支
     *
     * @param $order_id
     * @return array
     */
    public static function get_order_branch_by_order_id($order_id) {
        if (!$order_id) {
            return array();
        }

        $filter['order_id'] = $order_id;
        return _uri('order_branch', $filter);
    }

    /**
     * 通过订单表id，查询该订单的详细信息
     * @param  int 订单id号
     * @return array()
     */
    public static function get_order_relation_by_order_id($order_id, $order_by = '', $filter = array()) {
        if (!$order_id) {
            return array();
        }
        if ($order_by != '') {
            $order_by = ' ORDER BY `' . $order_by . '` DESC ';
        }

        $filter['order_id'] = $order_id;

        $order_relation_list = _model('order_relation')->getList($filter, $order_by);
        if (!$order_relation_list) {
            return array();
        }

        foreach ($order_relation_list as $k => $v) {
            $order_relation_list[$k]['goods_cover'] = goods_helper::sku_cover($v['sku_id']);
        }
        return $order_relation_list;
    }

    /**
     * 获取商品关系模型
     *
     * @param $order_id
     * @param string $relation_type
     * @return array
     * @throws AnException
     */
    public static function decorator_order_relation_model($order_id, $relation_type = '') {

        if (!$order_id) {
            return array();
        }

        $filter['order_id'] = $order_id;

        if ($relation_type && in_array($relation_type, array('exchange'))) {
            $relation_type = '_' . $relation_type;
        } else {
            $relation_type = '';
        }

        $table = 'order' . $relation_type . '_relation';

        $order_relation_list = _model($table)->getList($filter);

        if (!$order_relation_list) {
            return array();
        }

        foreach ($order_relation_list as $k => $v) {
            $v['goods_info'] = goods_helper::get_goods_info($v['goods_id']);
            $v['goods_cover'] = goods_helper::sku_cover($v['sku_id']);
            $v['category'] = goods_helper::get_goods_category_by_goods_id($v['goods_id'])['title'];
            $v['category_id'] = goods_helper::get_goods_category_by_goods_id($v['goods_id'])['id'];

            // TODO 方数, 体积
            $v['cube'] = $v['goods_info']['cube'] * $v['goods_num'];

            // TODO 重量
            $v['weight'] = $v['goods_info']['weight'] * $v['goods_num'];

            $order_relation_list[$k] = $v;
        }

        return $order_relation_list;
    }

    //检查是否有订单正在进行
    public static function check_order_ing($store_id) {
        $filter = array(
            'store_id' => $store_id,
            'status' => 1
        );
        $order_list = _model('order')->getList($filter);

        $is_order = 0;
        foreach ($order_list as $k => $v) {
            if (in_array($v['progress'], array(1, 3, 5))) {
                $is_order = $v['id'];
                break;
            }
        }
        return $is_order;
    }

    /**
     *通过订单表id，查询该订单的商品标题
     * @param   string 商品标题
     * @return  array()
     */
    public static function get_goods_title($order_id) {
        if (!$order_id) {
            return '';
        }

        $order_title = '';
        $order_relation_list = _model('order_relation')->getList(array('order_id' => $order_id));
        if ($order_relation_list) {
            $order_info = $order_relation_list[0];
            $order_title = _uri('sku_snapshot', $order_info['sku_snapshot_id'], 'goods_title') . '等商品';
        }

        return $order_title;
    }

    /**
     *通过订单id 查询当前订单的支付方式
     * @param   $order_id  int
     * @return  string
     */
    public static function get_pay_method($order_id) {
        return $order_id;
        //         if (!$order_id) {
        //             return '操作的订单不存在';
        //         }

        //         $pay_method = _uri('order', $order_id, 'pay_method');

        //         return $pay_method;
    }

    /**
     *订单id转订单编码
     * @param   $order_id  int
     * @return  string
     */
    public static function order_id_encode($order_id, $type = 1) {
        // liw modified
        // return $order_id;

        if (!$order_id) {
            return '操作的订单不存在';
        }

        if ($type == 2) {
            $refund_time = _uri('refund', (int)$order_id, 'add_time');
            $order_code = date('Ymd', strtotime($refund_time)) . '2' . $order_id;
        } else {
            $add_time = _uri('order', (int)$order_id, 'add_time');
            $order_code = date('Ymd', strtotime($add_time)) . '1' . $order_id;
        }

        return $order_code;
    }

    /**
     *订单编码转订单id
     * @param   $order_code  int
     * @return  string
     */
    public static function order_id_decode($order_code) {
        $order_id = substr($order_code, 9);
        $type = substr($order_code, 8, 1);
        if ($type == 1) {
            $add_time = _uri('order', (int)$order_id, 'add_time');
            if (!$add_time) {
                return '操作的订单不存在';
            }

            $new_order_code = date('Ymd', strtotime($add_time)) . '1' . $order_id;

            if ($new_order_code == $order_code) {
                return $order_id;
            }
        } /* else {
            // $add_time = _uri('refund', (int)$order_id, 'add_time');
            if (!$add_time) {
                return '操作的订单不存在';
            }

            $new_order_code = date('Ymd', strtotime($add_time)).'2'.$order_id;

            if ($new_order_code == $order_code) {
                return $order_id;
            }
        } */

        return '订单编码错误';
    }

    /**
     * 更新订单状态
     * @param   int or array() $order_id
     */
    public static function check_order_status($order_id = null) {
        $time = date('Y-m-d H:i:s', time() - 15 * 24 * 3600);
        $filter = array(
            'order_status' => 3,
            'status' => 1,
            '`express_time` <> ' => '',
            '`express_time` < ' => $time,
        );
        if ($order_id != null) {
            $filter['id'] = $order_id;
        }

        _model('order')->update($filter, array('order_status' => 4, 'sure_time' => date('Y-m-d H:i:s')));
    }

    /**
     * 更新订单取消状态
     * @param   int or array() $order_id
     */
    public static function cancel_order($order_id = null) {
        $time = date('Y-m-d H:i:s', time() - 3 * 24 * 3600);
        $filter = array(
            'order_status' => 1,
            'status' => 1,
            '`add_time` < ' => $time,
        );
        if ($order_id != null) {
            $filter['id'] = $order_id;
        }

        _model('order')->update($filter, array('order_status' => 5));

        // 返还库存
        $order_ids = _model('order')->getFields('id', $filter);
        if (!empty($order_ids)) {
            $order_relation_list = _model('order_relation')->getList(array('order_id' => $order_ids));
            foreach ($order_relation_list as $k => $v) {
                _model('sku')->update($v['sku_id'], ' SET `stock` = `stock` + ' . $v['goods_num']);
            }
        }
    }

    /**
     * 查看当前订单是否退款
     */
    public static function check_is_refund($order_relation_id) {
        if (!$order_relation_id) {
            return false;
        }

        $refund_info = _uri('refund', array('order_relation_id' => $order_relation_id));

        if (!empty($refund_info)) {
            return true;
        }

        return false;
    }

    /**
     * 查看当前订单是否退款
     */
    public static function check_refund_order_status($order_id) {
        if (!$order_id) {
            return false;
        }

        $order_relation_ids = _model('order_relation')->getFields('id', array('order_id' => $order_id));
        $refund_list = _model('refund')->getList(array('order_relation_id' => $order_relation_ids));
        $wait_refund = 0;
        $refunding = 0;
        if (!empty($refund_list)) {
            foreach ($refund_list as $k => $v) {
                if ($v['status'] == 1) {
                    $wait_refund++;
                    break;
                } elseif ($v['status'] == 2) {
                    $refunding++;
                }
            }
            if ($wait_refund > 0) {
                return 1;
            } elseif ($refunding > 0) {
                return 2;
            } else {
                return 3;
            }
        }

        return false;
    }

    /**
     * 查看当前订单是否处于退款状态
     */
    public static function check_refund_status($order_relation_id) {
        if (!$order_relation_id) {
            return false;
        }

        if (order_helper::check_is_refund($order_relation_id)) {
            $refund_status = _uri('refund', array('order_relation_id' => $order_relation_id), 'status');
            return $refund_status;
        }

        return false;
    }

    /**
     * 查看当前订单是否处于全部退款状态
     */
    public static function check_order_refund($order_id) {
        if (!$order_id) {
            return false;
        }

        $order_info = _uri('order', $order_id);
        $is_timeing = strtotime($order_info['sure_time']) + 7 * 24 * 3600 - time();
        if ($is_timeing < 0) {
            return '交易关闭';
        }

        $order_relation_ids = _model('order_relation')->getFields('id', array('order_id' => $order_id));

        $is_refunding = 0;
        $refund = 0;
        if (!empty($order_relation_ids)) {
            foreach ($order_relation_ids as $k => $v) {
                $refund_info = _uri('refund', array('order_relation_id' => $v));
                if (empty($refund_info)) {
                    continue;
                } elseif ($refund_info['status'] < 3) {
                    $is_refunding++;
                } else {
                    $refund++;
                }
            }

            if ($is_refunding > 0) {
                return '退款中';
            }
            if ($refund == count($order_relation_ids)) {
                return '交易关闭';
            }
        }

        return '交易完成';
    }

    /**
     * 获取退款金额
     */
    public static function get_refund_price($order_id) {
        $order_relation_ids = _model('order_relation')->getFields('id', array('order_id' => $order_id));
        if (empty($order_relation_ids)) {
            return 0;
        }

    }

    /**
     * 增加销量
     */
    public static function add_sale_num($order_id) {
        $order_relation_list = _model('order_relation')->getList(array('order_id' => $order_id));
        foreach ($order_relation_list as $k => $v) {
            $sku_info = _uri('sku', $v['sku_id']);
            _model('goods')->update($sku_info['goods_id'], ' SET `sale_count` = `sale_count` + ' . $v['goods_num']);
        }
    }

    /**
     * 返还商品销量
     */
    public static function refund_sale_num($order_id) {
        if (!$order_id) {
            return;
        }

        $order_relation_list = _model('order_relation')->getList(array('order_id' => $order_id));
        if (!$order_relation_list) {
            return;
        }
        foreach ($order_relation_list as $k => $v) {
            _model('goods')->update($v['goods_id'], ' SET `sale_count` = `sale_count` - ' . $v['goods_num']);
        }
    }

    /**
     * 计算订单杯数
     */
    public static function count_cup_num($cup_type, $num) {
        switch ($cup_type) {
            case '1':
                $small_cup = 75 * $num;
                $middle_cup = 0 * $num;
                $big_cup = 0 * $num;
                return array(
                    'small_cup' => $small_cup,
                    'middle_cup' => $middle_cup,
                    'big_cup' => $big_cup
                );
                break;
            case '5':
                $small_cup = 0 * $num;
                $middle_cup = 35 * $num;
                $big_cup = 0 * $num;
                return array(
                    'small_cup' => $small_cup,
                    'middle_cup' => $middle_cup,
                    'big_cup' => $big_cup
                );
                break;
            case '10':
                $small_cup = 0 * $num;
                $middle_cup = 0 * $num;
                $big_cup = 25 * $num;
                return array(
                    'small_cup' => $small_cup,
                    'middle_cup' => $middle_cup,
                    'big_cup' => $big_cup
                );
                break;
            case '15':
                $small_cup = 37 * $num;
                $middle_cup = 18 * $num;
                $big_cup = 0 * $num;
                return array(
                    'small_cup' => $small_cup,
                    'middle_cup' => $middle_cup,
                    'big_cup' => $big_cup
                );
                break;
            case '20':
                $small_cup = 0 * $num;
                $middle_cup = 18 * $num;
                $big_cup = 13 * $num;
                return array(
                    'small_cup' => $small_cup,
                    'middle_cup' => $middle_cup,
                    'big_cup' => $big_cup
                );
                break;
            case '25':
                $small_cup = 37 * $num;
                $middle_cup = 0 * $num;
                $big_cup = 13 * $num;
                return array(
                    'small_cup' => $small_cup,
                    'middle_cup' => $middle_cup,
                    'big_cup' => $big_cup
                );
                break;
            case '30':
                $small_cup = 25 * $num;
                $middle_cup = 9 * $num;
                $big_cup = 8 * $num;
                return array(
                    'small_cup' => $small_cup,
                    'middle_cup' => $middle_cup,
                    'big_cup' => $big_cup
                );
                break;
            default:
                return array();
                break;
        }
    }

    /**
     * 返回订单库存
     */
    public static function refund_stock($order_id) {
        if (!$order_id) {
            return;
        }

        $order_relation_list = _model('order_relation')->getList(array('order_id' => $order_id));
        if (!$order_relation_list) {
            return;
        }
        foreach ($order_relation_list as $k => $v) {
            _model('sku')->update($v['sku_id'], ' SET `stock` = `stock` + ' . $v['goods_num']);
        }
    }

    /**
     * 自动处理订单状态
     * @param  [type]
     * @return [int] 订单状态
     */
    public static function auto_status($order_id, $pay_time = 1, $deliver_time = 15) {
        if (!$order_id) {
            return 0;
        }

        $order_info = _uri('order', $order_id);
        if (!$order_info) {
            return 0;
        }

        if ($order_info['progress'] == 1) {
            $buy_time = strtotime($order_info['add_time']);
            if (($buy_time + 3600 * 24 * $pay_time) > time()) { // 24小时未付款 自动取消订单
                return 1;
            }

            _model('order')->update(array('id' => $order_id), array('progress' => 0));

            self::refund_stock($order_id); //返回库存

            return 0;
        } elseif ($order_info['progress'] == 15) {
            $deliver_time = strtotime($order_info['deliver_time']);
            if (($deliver_time + 3600 * 24 * $deliver_time) > time()) {  // 15天未收货 自动收获
                return 15;
            }

            _model('order')->update(array('id' => $order_id), array(
                'progress' => 20,
                'receiver_time' => date('Y-m-d H:i:s')
            ));

            return 20;
        }

        return $order_info['progress'];
    }


    /**
     * 发送发货短信
     */
    public static function sendExpressMessage($send_type, $code, $mobile = '', $email = '') {
        $template = sms_config::$replace_template;
        if (isset($template[$send_type])) {
            $template = $template[$send_type];
        }

        // 只发送短信
        if (is_array($mobile) || $mobile != '') {
            $send_sms_template = sms_config::$send_sms_template;
            $send_sms_template = $send_sms_template[$send_type];
            if ($code) {
                $send_content = str_replace($template, $code, $send_sms_template);
            } else {
                $send_content = $send_sms_template;
            }

            if (is_array($mobile)) {
                foreach ($mobile as $k => $v) {
                    if (!$v) {
                        continue;
                    }
                    $status = sms_helper::send_sms($v, $send_type, $send_content);
                }
            } else {
                $status = sms_helper::send_sms($mobile, $send_type, $send_content);
            }
        }
        if ($email != '') {
            $send_mail_content = mail_config::$send_mail_content;
            $send_title = $send_mail_content[$send_type]['title'];

            if ($code != '') {
                $mail_url = ROOT_PATH . '/template/default/mail/' . $send_type . '.html';
                $mail_str = file_get_contents($mail_url);
                $content = str_replace($template, $code, $mail_str);
            } else {
                $content = $send_mail_content[$send_type]['content'];
            }

            mail_helper::mail($email, $send_title, $content, 'HTML');
        }
    }

    /**
     * 查询订单是否可以显示给用户电子发票链接，可以则返回电子发票链接
     */
    public static function get_order_refund_url($order_id) {
        $order_info = _uri('order', $order_id);
        if (!$order_info) {
            return false;
        }
        if ($order_info['status'] == 0 || $order_info['progress'] != 20) {
            return false;
        }
        if (!$order_info['Einvoice_id']) {
            return false;
        }
        $Einvoice_info = _uri('Einvoice', $order_info['Einvoice_id']);
        if (!$Einvoice_info) {
            return false;
        }
        $refund_info = _model('refund')->read(array('order_id' => $order_id, 'type' => '1', 'status' => '1'));
        if (!$refund_info) {
            return $Einvoice_info['pdf_url'];
        }
        if ($refund_info['refund_status'] == 20) {
            return false;
        }
        return $Einvoice_info['pdf_url'];
    }


    /**
     * 获取支付地址
     */
    public static function get_order_pay_url($order_id) {
        $order_info = _uri('order', $order_id);
        if ($order_info['pay_type'] == 2) {
            return AnUrl('order/' . $order_id . '?showwxpaytitle=1&direct_pay=1');
        } else {
            if (user_helper::get_login_way() == 'lenovowap') {
                return AnUrl('order/' . $order_id . '?direct_pay=1');
            } else {
                return AnUrl(openapi_config::$pay_type[$order_info['pay_type']]['module'] . '?order_id=' . $order_id);
            }
        }
    }

    /**
     * 获取店铺订单总数
     * @param  [type] $store_id [description]
     * @return [type]           [description]
     */
    public static function get_store_order_num($store_id, $filter = array()) {
        $filter = array_extend(array(
            'store_id' => $store_id,
            'status' => 1
        ), $filter);
        $order_num = _model('order')->getTotal($filter);
        return $order_num;
    }

    /**
     * 对比两个经销商用户进货价是否相同
     */
    public static function contrast_user_price($user_id, $other_user_id) {
        if (!$user_id || !$other_user_id) {
            return false;
        }
        $user_store_info = _uri('user_store', array('user_id' => $user_id));
        $other_user_store_info = _uri('user_store', array('user_id' => $other_user_id));

        if ($user_store_info['addon_price'] == $other_user_store_info['addon_price']) {
            return 1;
        } else {
            return 0;
        }
    }

    /**
     * 是否第一次进货
     * @param  [type]  $store_id [description]
     * @return boolean           [description]
     */
    public static function is_first_trade($store_id) {

    }

    /**
     * 获取销售助理所属经销商的所有的订单数量
     */
    public static function get_assistant_dealer_order_total_num($user_id) {
        if (!$user_id) {
            return 0;
        }

        $dealer_list = user_helper::get_dealer_list_by_assistant_user_id($user_id);
        $order_num = 0;
        if ($dealer_list) {
            foreach ($dealer_list as $key => $val) {
                // 查询订单数
                $order_num += SELF::get_order_num_by_user_id($val['id']);
            }
        } else {
            return 0;
        }

        return $order_num;

    }

    /**
     * 查询某用户的订单数
     */
    public static function get_order_num_by_user_id($user_id) {
        if (!$user_id) {
            return 0;
        }

        return _model('order')->getTotal(array('user_id' => $user_id, 'progress' => array(1, 3)));

    }

    /**
     * 获取指定门店的所有订单列表
     */
    public static function get_store_order_list($store_id, $filter = array()) {
        if (!$store_id) {
            return array();
        }

        $filter['store_id'] = $store_id;

        return _model('order')->getList($filter);

    }

    /**
     * 更新订单时间
     */
    public static function update_order_time($order_id, $time_type) {
        if (!$order_id && !$time_type) {
            return false;
        }
        _model('order')->update($order_id, array("$time_type" => date('Y-m-d H:i:s')));
    }

    /**
     * 时长格式化
     */
    public static function time_format($time_long) {
        $format = '';
        if ($time_long >= 86400) {
            $format .= floor($time_long / 86400) . '天';
            $time_long = $time_long % 86400;
        }
        if ($time_long >= 3600) {
            $format .= floor($time_long / 3600) . '小时';
            $time_long = $time_long % 3600;
        }
        if ($time_long >= 60) {
            $format .= floor($time_long / 60) . '分';
            $time_long = $time_long % 60;
        }
        $format .= $time_long . '秒';

        return $format;
    }

    /**
     * 根据订单id获取送货单状态
     *
     * @param $order_id
     * @return null
     * @throws AnException
     */
    public static function get_order_delivery_note_status_by_order_id($order_id) {
        $list = _model('order_delivery_note')->getFields('status', array('order_id' => $order_id));
        return count($list) ? $list[0] : null;
    }

    /**
     * 根据订单id获取送货单详情
     *
     * @param $order_id
     * @return array
     * @throws AnException
     */
    public static function get_order_delivery_note_info_by_order_id($order_id) {
        $list = _model('order_delivery_note')->getList(array('order_id' => $order_id));
        if (!empty($list) && isset($list[0])) {
            $list[0]['path'] = _image($list[0]['path']);
            // 抱抱币取整
            $list[0]['return_bbcoin'] = sprintf("%d", $list[0]['return_bbcoin']);
            return $list[0];
        }
        return array();
    }

    /**
     * 根据订单id创建送货单
     *
     * @param $order_id
     * @throws AnException
     */
    public static function create_order_delivery_note_by_order_id($order_id) {
        // TODO 直接使用 self::count_original_price_by_order_id($order_id) 计算成本及抱抱币
        //成本
        $original_price = order_helper::count_original_price_by_order_id($order_id);
        //订单总金额
        //$price = _model('order')->getFields( 'price', array( 'id'=>$order_id ) );
        $order_info = _model('order')->getList(array('id' => $order_id));
        if (!$order_info) {
            return false;
        }
        $price = $order_info[0]['price'];
        //应返抱抱币
        $bbcoin = $price - $original_price;

        $info = array(
            //'id'自增，不需要添加
            'order_id' => $order_id,
            'status' => 0,
            'return_cash' => $original_price,
            'return_bbcoin' => $bbcoin,
        );

        _model('order')->update(array('id' => $order_id), array('delivery_note_status' => 0));
        $ret = _model('order_delivery_note')->create($info);
        if (!$ret) {
            return false;
        }

        return true;
    }

    /**
     * 计算成本/余额   xdq added on 2016-07-06
     *
     * @param $order_id
     * @return {array}
     * @throws AnException
     */
    public static function count_original_price_by_order_id($order_id) {
        $filter['order_id'] = $order_id;
        $order_balance = 0;
        $order_relation = _model('order_relation')->getList($filter);
        foreach ($order_relation as $k => $v) {
            $sku_info = _uri('sku', array('id' => $v['sku_id']));
            $order_balance += $sku_info['price'] * $v['goods_num'];
        }

        return $order_balance;
    }

    /**
     * 取消订单, 退回余额和抱抱币
     *
     * @param $order_id
     */
    public static function cancel_order_send_back($order_id = null, $reason = '') {
        if (empty($order_id)) {
            return false;
        }

        $order_info = _uri('order', $order_id);

        if ($order_info['pay_user_money'] > 0) {
            user_money_helper::change_user_money(array(
                'user_id' => $order_info['user_id'],
                'res_id' => user_money_config::RES_TYPE_CANCEL_ORDER_SENDBACK, // 取消订单
                'user_money' => 1 * $order_info['pay_user_money'],
                'extra' => $reason,
                'order_id' => $order_id,
                'admin_id' => user_helper::get_user_id(),
            ));
        }

        if ($order_info['pay_bbcoin'] > 0) {
            bbcoin_helper::change_bbcoin(array(
                'user_id' => $order_info['user_id'],
                'res_id' => bbcoin_config::RES_TYPE_CANCEL_ORDER_SENDBACK, // 取消订单
                'bbcoin' => 1 * $order_info['pay_bbcoin'],
                'extra' => $reason,
                'order_id' => $order_id,
                'admin_id' => user_helper::get_user_id(),
            ));
        }

        return true;
    }

    /**
     * 进货/兑换等, 确认到货一并下发
     *
     * @param null $order_id
     * @param string $reason
     * @return bool
     */
    public static function confirm_store_order_send_addition($order_id = null, $reason = '') {

        if (empty($order_id)) {
            return false;
        }

        $order_info = _uri('order', $order_id);

        // 必须是门店(终端)订单
        if (empty($order_info) || $order_info['type'] != order_config::ORDER_TYPE_STORE) {
            return false;
        }

        // 兑换 - 返给合伙人抱抱币
        if ($order_info['pay_bbcoin'] > 0) {
            bbcoin_helper::change_bbcoin(array(
                'user_id' => $order_info['agency_id'],
                'res_id' => bbcoin_config::RES_TYPE_EXCHANGE_SEND_DEALER,
                'bbcoin' => 1 * $order_info['pay_bbcoin'],
                'extra' => $reason,
                'order_id' => $order_id,
            ));
        }

        $order_branch = _uri('order_branch', array('order_id' => $order_id));

        // 散装进货 - 返给合伙人或者门店抱抱币
        if ($order_branch && $order_branch['is_bbcoin_enable'] == 1 && $order_branch['bbcoin'] > 0) {

            $agency_info = user_helper::get_user_info($order_info['agency_id']);

            // 合伙人剩余额度
            $new_bbcoin = $agency_info['order_total_bbcoin'] - $order_branch['bbcoin'];

            // 扣到0为止
            if ($new_bbcoin < 0) {
                $new_bbcoin = 0;

                $actual_change = $agency_info['order_total_bbcoin'];
                // 溢出部分添加到备注
                $reason .= ($reason ? ', ' : '') .
                           '应奖励:' .
                           intval($order_branch['bbcoin']) .
                           ' 实际奖励:' .
                           intval($actual_change) .
                           ' 合伙人进货额度不足:' .
                           intval($order_branch['bbcoin'] - $actual_change);

                // 实际的变化值
                $bbcoin = $actual_change;
            } else {
                $bbcoin = $order_branch['bbcoin'];
            }

            // 从进货奖励总额度中扣除
            _model('user')->update(array('id' => $order_info['agency_id']), array(
                'order_total_bbcoin' => $new_bbcoin,
            ));

            if ($order_branch['store_type'] == store_config::TYPE_CINEMA) { // 如果是影院, 返还给合伙人
                $target = $order_info['agency_id'];
                $res_id = bbcoin_config::RES_TYPE_BULK_REWARD_SEND_DEALER;
            } else { // 其他的返还门店
                $target = $order_info['user_id'];
                $res_id = bbcoin_config::RES_TYPE_BULK_REWARD;
            }

            bbcoin_helper::change_bbcoin(array(
                'user_id' => $target,
                'res_id' => $res_id,
                'bbcoin' => intval($bbcoin),
                'extra' => $reason,
                'order_id' => $order_id,
            ));
        }

        return true;
    }

    public static function confirm_dealer_order_send_addition($order_id) {
        if (empty($order_id)) {
            return false;
        }

        $order_info = _uri('order', $order_id);

        // 确认必须到货状态
        if (empty($order_info) || $order_info['type'] != order_config::ORDER_TYPE_DEALER) {
            return false;
        }

        // 如果当前订单含有二级差价
        if ($order_info['is_diff_price'] == 1) {
            $dealer_info = user_helper::get_user_info($order_info['user_id']);
            $parent_dealer_info = user_helper::get_user_info($dealer_info['parent_id']);
            // 二级合伙人允许返还
            if ($dealer_info['is_return_diff'] == 1) {
                $ret = _model('order')->update(array('id' => $order_info['id']), array('return_diff_time' => datetime()));
                api_helper::_p('返还二级余额');
                if ($ret) {
                    user_money_helper::change_user_money(array(
                        'user_id' => $parent_dealer_info['id'],
                        'user_money' => $order_info['diff_sum_price'],
                        'res_id' => user_money_config::RES_TYPE_SUB_DEALER_RETURN_DIFF,
                        'order_id' => $order_info['id'],
                    ));
                }
            }
        }
    }

    /**
     * 订单委派
     *
     * @param int $order_id
     * @param int $service_agency_id
     * @return bool
     * @throws AnException
     */
    public static function set_order_service_agency($order_id = 0, $service_agency_id = 0) {

        if ($order_id == 0 || $service_agency_id == 0) {
            return false;
        }

        $order_info = _uri('order', $order_id);

        if (empty($order_info)) {
            // 订单不存在
            return false;
        }

        if ($order_info['progress'] != 1 || $order_info['assigned_id'] > 0) {
            // 当前合伙人已经处理过, 分配过, 无法委派
            return false;
        }

        $agency_id = $order_info['agency_id'];

        if ($service_agency_id == $agency_id) {
            // 委派目标和原始值相同, 无需委派
            return false;
        }

        $service_agency_info = _uri('user', $service_agency_id);

        if (empty($service_agency_info)) {
            // 委派目标不合法
            return false;
        }

        $filter = array('id' => $order_id);

        if ($order_info['original_agency_id'] > 0) {
            // 已经委派过

            if ($order_info['original_agency_id'] == $service_agency_id) {
                // 又派回来了!
                $data = array('agency_id' => $service_agency_id, 'original_agency_id' => 0);
            } else {
                // 只变更委派目标
                $data = array('agency_id' => $service_agency_id);
            }
        } else {
            // 没委派过, 原始合伙人保存并设置新合伙人
            $data = array('agency_id' => $service_agency_id, 'original_agency_id' => $agency_id);
        }

        $ret = _model('order')->update($filter, $data);

        self::add_order_delegation_record(array(
            'order_id' => $order_id,
            'original_id' => $agency_id,
            'target_id' => $service_agency_id,
            'admin_id' => user_helper::get_user_id(),
            'res_id' => 1, // 指定合伙人
        ));

        if ($ret) {
            return true;
        }

        return false;
    }

    /**
     * 记录订单委派操作
     *
     * @param array $param
     * @return bool
     * @throws AnException
     */
    public static function add_order_delegation_record($param = array()) {

        $rule = array(
            'order_id' => 0,
            'original_id' => 0,
            'target_id' => 0,
            'role_id' => 0,
            'admin_id' => 0,
            'add_time' => datetime(),
            'res_id' => 0,
        );

        $record = parse_param($rule, $param);

        if (!($record['order_id'] && $record['target_id'] && $record['original_id'])) {
            return false;
        }

        if ($record['admin_id'] > 0) {
            $record['role_id'] = user_helper::get_user_role_id($record['admin_id']);
        }

        $res = _model('order_delegation_record')->create($record);

        return $res ? true : false;
    }

    /**
     * 订单数据模型
     *
     * 后台用
     *
     * @param array $order_list
     * @return array
     * @throws AnException
     */
    public static function decorator_order_model($order_list = array()) {

        $area_fields = array('province', 'city', 'county');

        foreach ($order_list as $k => $v) {
            // 货品明细
            $v['order_relation'] = order_helper::decorator_order_relation_model($v['id']);
            $v['order_relation_count'] = count($v['order_relation']);
            $v['order_relation_cube'] = num_keep_two_round(array_sum(array_column($v['order_relation'], 'cube')));
            $v['order_relation_weight'] = num_keep_two_round(array_sum(array_column($v['order_relation'], 'weight')));

            // 兑换明细
            $v['order_exchange_relation'] = order_helper::decorator_order_relation_model($v['id'], 'exchange');
            $v['order_exchange_relation_count'] = count($v['order_exchange_relation']);
            $v['order_exchange_relation_cube'] = num_keep_two_round(array_sum(array_column($v['order_exchange_relation'], 'cube')));
            $v['order_exchange_relation_weight'] = num_keep_two_round(array_sum(array_column($v['order_exchange_relation'], 'weight')));

            // 总方数
            $v['order_cube'] = num_keep_two_round($v['order_relation_cube'] + $v['order_exchange_relation_cube']);

            // 总重量
            $v['order_weight'] = num_keep_two_round($v['order_relation_weight'] + $v['order_exchange_relation_weight']);

            // 商品总量
            $v['order_goods_count'] = $v['order_relation_count'] + $v['order_exchange_relation_count'];

            // [终端使用]送货单明细
            if (isset($v['delivery_note_status']) && $v['delivery_note_status'] >= 0) {
                $v['order_delivery_note'] = order_helper::get_order_delivery_note_info_by_order_id($v['id']);
            }

            // 掌柜门店
            $v['store_info'] = store_helper::get_store($v['store_id']);

            // 掌柜明细
            $v['store_user_info'] = user_helper::get_user_info($v['user_id']);

            // 掌柜所属群组
            $v['store_user_role'] = user_helper::get_user_role_id($v['user_id']);

            // 原始合伙人
            if ($v['original_agency_id'] > 0) {
                $v['original_dealer_info'] = user_helper::get_user_info($v['original_agency_id']);
            }

            // [合伙人]
            if ($v['type'] == 1) {
                $v['dealer_info'] = $v['store_user_info'];

                // 收货地址处理
                if (empty($v['dealer_address'])) {
                    $v['dealer_address'] = $v['dealer_info']['store_house'];
                }
                if (empty($v['receiver'])) {
                    $v['receiver'] = $v['dealer_info']['realname'];
                }
                if (empty($v['mobile'])) {
                    $v['mobile'] = $v['dealer_info']['mobile'];
                }

                // 处理地区
                if (!empty($v['county_code']) && $v['county_code'] != '000000') {
                    $area_code = $v['county_code'];
                } elseif (!empty($v['city_code']) && $v['city_code'] != '000000') {
                    $area_code = $v['city_code'];
                } elseif (!empty($v['province_code']) && $v['province_code'] != '000000') {
                    $area_code = $v['province_code'];
                } else {
                    $area_code = $v['dealer_info']['area_code'];
                }

                $codes = area_helper::parse_area_code($area_code);
                foreach ($area_fields as $area_type => $field) {
                    $v[$field] = isset($codes[$area_type]['area']) ? $codes[$area_type]['area'] : '';
                    $v[$field . '_code'] = isset($codes[$area_type]['area_code']) ? $codes[$area_type]['area_code']
                        : '000000';
                }

                $v['region'] = join(' ', array_filter(array($v['province'], $v['city'], $v['county'])));
            } else {
                $v['dealer_info'] = user_helper::get_user_info($v['agency_id']);
            }

            $order_list[$k] = $v;
        }

        return $order_list;
    }

    /**
     * [订单导出模板]
     * @param  array $data [description]
     * @return [type]       [description]
     */
    public static function decorator_order_export($data = array()) {
        $order = array();
        foreach ($data as $key => $value) {
            //订单编号(流水号)
            $order[$key]['order_id'] = " " . order_helper::order_id_encode($value['id']);
            $order[$key]['order_time'] = $value['add_time'];
            $order[$key]['id'] = $value['id'];
            //订单状态
            $order[$key]['order_status'] = order_config::$store_progress[$value['progress']];
            //订单类型
            $order[$key]['order_type'] = order_config::$order_type[$value['type']];
            //订单总价
            $order[$key]['order_price'] = " " . $value['price'];
            //订单类型
            $order[$key]['order_pay_type'] = order_config::$pay_type[$value['pay_type']];
            //支付时间
            $pay_time = strtotime($value['pay_time']) ? '未支付' : $value['pay_time'];
            $order[$key]['order_pay_time'] = $pay_time;
            //合伙人信息
            $order[$key]['partner_name'] = $value['dealer_info']['realname'];
            $order[$key]['partner_phone'] = $value['dealer_info']['mobile'];
            //店铺信息
            $order[$key]['store_id'] = $value['store_info']['id'];
            $order[$key]['store_name'] = $value['store_info']['title'] . ' - ' . $value['store_info']['title_branch'];
            $order[$key]['store_addr'] = $value['store_info']['address'];
            $order[$key]['store_owner'] = user_helper::get_realname_by_id($value['user_id']);
            //收货人信息
            $address = "收货人:" . $value['receiver'] . "(" . $value['mobile'] . ")" . " \r收货地址:" . $value['address'];
            $order[$key]['receiver'] = $address;

            //送货单状态
            $delivery_status = order_config::$delivery_status[$value['delivery_note_status']];
            $order[$key]['order_delivery_status'] = $delivery_status;

            $order[$key]['goods_info'] = array();
            $price = 0;
            //现付商品信息
            foreach ($value['order_relation'] as $goodsKey => $relation) {
                $goods_info = goods_helper::get_goods_info($relation['goods_id']);
                $order[$key]['goods_info'][$goodsKey]['goods_name'] = $goods_info['title'];
                $order[$key]['goods_info'][$goodsKey]['amount'] = $relation['goods_num'];
                $order[$key]['goods_info'][$goodsKey]['price'] = " " . $relation['real_price'];
                $cup_type = ($relation['cup_type'] == 0) ? '没有散装商品' : '散装商品';
                $order[$key]['goods_info'][$goodsKey]['cup_type'] = $cup_type;
                $order[$key]['goods_info'][$goodsKey]['exchange_amount'] = 0;
                $order[$key]['goods_info'][$goodsKey]['exchange_total_price'] = 0;

                $price += $relation['real_price']; //实际支付
            }
            //兑换商品
            foreach ($value['order_exchange_relation'] as $exchange) {
                $exchange_goods_info = goods_helper::get_goods_info($relation['goods_id']);
                $exchange_goods = array(
                    'goods_name' => $exchange_goods_info['title'],
                    'amount' => 0,
                    'price' => 0,
                    'cup_type' => '没有散装商品',
                    'exchange_amount' => $exchange['goods_num'],
                    'exchange_total_price' => " " . $exchange['real_price']
                );
                array_push($order[$key]['goods_info'], $exchange_goods);
            }
            //订单中的商品数量
            $order[$key]['total_amount'] = $value['goods_num'] + $value['exchange_num'];
            $order[$key]['pay_price'] = " " . $price; //实际支付
        }
        return $order;
    }

    public static function cup_list($cup_type) {
        if ($cup_type == 'small') {
        }
    }

    /**
     * 合伙人的抱抱币奖励额度上限
     * 合伙人确认收货时, 根据订单进行添加
     *
     * @param $order_id
     * @return bool
     * @throws AnException
     */
    public static function add_dealer_order_total_bbcoin($order_id) {
        if (!$order_id) {
            return false;
        }

        $user_id = _uri('order', $order_id, 'user_id');
        $goods_ids = goods_helper::get_goods_ids_by_category_ids(goods_config::CATEGORY_BULK);

        if (!$user_id || empty($goods_ids)) {
            return false;
        }

        $filter = array();
        // 获取散装商品ID
        $filter['goods_id'] = $goods_ids;

        $goods = order_helper::get_order_relation_by_order_id($order_id, '', $filter);
        $goods_sum_num = array_sum(array_column($goods, 'goods_num'));

        $bbcoin = order_config::$reward['bulk_bbcoin'] * $goods_sum_num;

        $origin_bbcoin = _uri('user', $user_id, 'order_total_bbcoin');

        $ret = _model('user')->update(array('id' => $user_id), array(
            'order_total_bbcoin' => $origin_bbcoin + $bbcoin
        ));

        return $ret ? true : false;
    }

    /**
     * 合伙人订单到货操作
     * APP 后台公用
     *
     * @param $order_id
     * @param string $extra
     * @return array
     * @throws AnException
     */
    public static function DEALER_ACTION_DONE($order_id, $extra = '') {

        if (!$order_id) {
            return array(1, '无效的订单');
        }

        $order_info = _uri('order', $order_id);

        if (!$order_info ||
            ($order_info['progress'] != order_config::DEALER_SENDING &&
             $order_info['progress'] != order_config::DEALER_SENDING_OLD)
        ) {
            return array(1, '现在还不能做这样的操作');
        }

        $info = array(
            'progress' => order_config::DEALER_DONE,
            'receiver_time' => datetime(),
        );

        if ($extra) {
            $info_branch = array(
                'receiver_type' => 2,
                'receiver_extra' => $extra,
            );
        } else {
            $info_branch = array(
                'receiver_type' => 1,
            );
        }

        // TODO TS事物改造
        $ret = _model('order')->update(array('id' => $order_info['id']), $info);

        if ($ret) {

            _model('order_branch')->update($order_info['id'], $info_branch);

            // 增加开票额度
            invoice_helper::change_user_invoice_amount($order_info['user_id'], $order_info['price'], 1, 1);

            // 增加合伙人抱抱币奖励池额度
            order_helper::add_dealer_order_total_bbcoin($order_info['id']);

            // TODO 等积分改完了, 就改这个
            $user_info = _uri('user', $order_info['user_id']);
            $store_info = _uri('store', $order_info['store_id']);
            _widget('dealers')->confirm_order_arrival($user_info, $order_info['store_id'], $store_info, $order_info, $order_id);

            // 订单完成下发项目
            order_helper::confirm_dealer_order_send_addition($order_info['id']);

            // 创建记录
            order_helper::record_dealer_order_operation($order_info['id'], order_config::DEALER_DONE, order_config::DEALER_ACTION_DONE);

            return array(0, '确认到货成功');
        }

        return array(1, '操作失败, 请稍后重试');
    }

    /**
     * 合伙人订单取消操作
     * APP 后台公用
     *
     * @param $order_id
     * @param string $extra
     * @throws AnException
     */
    public static function DEALER_ACTION_CANCEL($order_id, $extra = '') {

        if (!$order_id) {
            return array(1, '无效的订单');
        }

        $order_info = _uri('order', $order_id);

        if (!$order_info ||
            ($order_info['progress'] != order_config::DEALER_WAIT_PAY &&
             $order_info['progress'] != order_config::DEALER_WAIT_PAY_OLD &&
             $order_info['progress'] != order_config::DEALER_WAIT_CONFIRM)
        ) {
            return array(1, '现在还不能做这样的操作');
        }

        $info = array(
            'progress' => order_config::DEALER_CANCEL,
            'reason' => $extra,
            'cancel_order_time' => datetime(),
            'cancel_order_user_id' => user_helper::get_user_id(),
        );

        $ret = _model('order')->update($order_id, $info);

        if ($ret) {
            order_helper::cancel_order_send_back($order_id, $extra);
            // 记录流水
            order_helper::record_dealer_order_operation($order_info['id'], order_config::DEALER_CANCEL, order_config::DEALER_ACTION_CANCEL, json_encode(array($extra)));

            return array(0, '取消订单成功');
        }

        return array(1, '操作失败, 请稍后重试');

    }
}

?>
